#include "friendmodel.hpp"
#include "db/db.h"
#include <muduo/base/Logging.h>
#include "mysql_conn_pool.hpp"

bool friendModel::haveUser(int friendid){
    char sql[128]={0};
    sprintf(sql,"select * from `user` where id='%d'",friendid);

    //从数据库连接池中获取连接对象，并且使用RAII机制
    MySQL* mysql = nullptr;
    mysql_connpool_RAII RAII(&mysql,mysql_connPool::getInstance());

    if(mysql!=nullptr){
        MYSQL_RES* res=mysql->query(sql);
        if(mysql_fetch_row(res)==nullptr){
            //查询结果没有用户则返回false
            mysql_free_result(res);
            return false;
        }
        mysql_free_result(res);
        return true;
    }
    
    return false;
}

//添加好友
void friendModel::insert(int userid,int friendid){
    char sql[1024]={0};
    sprintf(sql,"insert into `friend` values(%d,%d)",userid,friendid);
     
    //从数据库连接池中获取连接对象，并且使用RAII机制
    MySQL* mysql = nullptr;
    mysql_connpool_RAII RAII(&mysql,mysql_connPool::getInstance());
    if(mysql!=nullptr){
        mysql->update(sql);
    }

}

//返回好友列表，通过用户id查询它的好友信息
vector<User> friendModel::query(int userid){
    char sql[256];
    sprintf(sql,
        "select a.id,a.name,a.state from user a inner join friend b on a.id=b.friendid where b.userid = %d",userid);
    
    vector <User> vec;
    
    //从数据库连接池中获取连接对象，并且使用RAII机制
    MySQL* mysql = nullptr;
    mysql_connpool_RAII RAII(&mysql,mysql_connPool::getInstance());

    if(mysql!=nullptr){
        MYSQL_RES* res=mysql->query(sql);
        if(res!=nullptr){
            MYSQL_ROW row;
            //不断读取每一行结果，并将查询到的好友id，好友名字，好友状态添加到数组中
            while((row=mysql_fetch_row(res))!=nullptr){
                User user;
                user.setID(atoi(row[0]));
                user.setName(row[1]);
                user.setState(row[2]);

                vec.push_back(user);

            }
            mysql_free_result(res);
            return vec;
        }
        mysql_free_result(res);
    }
    return {};
}